import _ from 'lodash';
import React, {Component} from 'react';
import {ScrollView, StyleSheet, Alert, Image} from 'react-native'; // 确保引入了 Image
import {
  Avatar,
  AvatarHelper,
  View,
  Text,
  Colors,
  Typography,
  AvatarProps,
  Badge,
  Button,
} from 'react-native-ui-lib';
import {TestCase, TestSuite} from '@rnoh/testerino';

// 图标资源
const star = require('../../assets/icons/star.png');
const onlineColor = Colors.$backgroundSuccessHeavy;

// 定义用例接口
interface Example extends AvatarProps {
  title: string;
}

// 1. 基础显示与内容 (Content & Source)
const contentExamples: Example[] = [
  {
    title: 'Source: Image URL',
    source: {
      uri: 'https://randomuser.me/api/portraits/women/20.jpg',
    },
    size: 50,
  },
  {
    title: 'Source: Image Source(loacal file)',
    source: require('../../assets/images/card-example.jpg'),
    size: 50,
  },
  {
    title: 'Label: Explicit Text(RN)',
    label: 'RN',
    backgroundColor: Colors.violet60,
    size: 50,
  },
  {
    title: 'Label: Explicit Text(Test)',
    label: 'Test',
    backgroundColor: Colors.violet60,
    size: 50,
  },
  {
    title: 'Name: Auto Initials (John Doe -> JD)',
    name: 'John Doe',
    backgroundColor: Colors.orange40,
    size: 50,
  },
  {
    title: 'Name: Auto Initials (Jackie Chan -> JC)',
    name: 'Jackie Chan',
    backgroundColor: Colors.orange40,
    size: 50,
  },
  {
    title: 'Label Color: Colors.yellow30\nbackgroundColor: Colors.blue30',
    label: 'AB',
    labelColor: Colors.yellow30,
    backgroundColor: Colors.blue30,
    size: 50,
  },
  {
  title: 'Label Color: Colors.Colors.blue30\nbackgroundColor: Colors.yellow30',
    label: 'AB',
    labelColor: Colors.blue30,
    backgroundColor: Colors.yellow30,
    size: 50,
  },
];

// 2. 自动背景色 (Auto Colors)
const autoColorExamples: Example[] = [
  {
    title: 'useAutoColors: True\n(Adam Sandler)',
    name: 'Adam Sandler',
    useAutoColors: true,
    size: 50,
  },
  {
    title: 'useAutoColors: True\n(Zoe Saldana)',
    name: 'Zoe Saldana',
    useAutoColors: true,
    size: 50,
  },
  {
    title: 'autoColorsConfig: Custom Palette',
    name: 'Zoe Saldana',
    useAutoColors: true,
    autoColorsConfig: {
      avatarColors: [Colors.red30, Colors.blue30, Colors.green30],
      hashFunction: (name?: string) => 0, // 强制命中某个颜色
    },
    size: 50,
  },
];

// 3. 样式与尺寸 (Style & Size)
const styleExamples: Example[] = [
  {
    title: 'Size: 80 (Large)',
    label: 'XL',
    size: 80,
    backgroundColor: Colors.blue30,
  },
  {
    title: 'Size: 30 (Small)',
    label: 'XS',
    size: 30,
    backgroundColor: Colors.blue30,
  },
  {
    title: 'Container Style: Border purple',
    source: {uri: 'https://randomuser.me/api/portraits/women/44.jpg'},
    containerStyle: {
      borderWidth: 0.8,
      borderColor: Colors.purple30,
      shadowColor: '#000',
      shadowOffset: {width: 0, height: 0},
      shadowOpacity: 0.5,
      shadowRadius: 3,
    },
    size: 60,
  },
  {
    title: 'Container Style: Border ',
    source: {uri: 'https://randomuser.me/api/portraits/women/44.jpg'},
    containerStyle: {
      borderWidth: 0.8,
      borderColor: Colors.red30,
      shadowColor: '#000',
      shadowOffset: {width: 10, height: -10},
      shadowOpacity: 0.5,
      shadowRadius: 3,
    },
    size: 60,
  },
  {
    title: 'Image Style: Opacity 0.3',
    source: {uri: 'https://randomuser.me/api/portraits/men/32.jpg'},
    imageStyle: {opacity: 0.3},
    backgroundColor: Colors.black,
    size: 60,
  },
  {
    title: 'Image Style: Opacity 0.6',
    source: {uri: 'https://randomuser.me/api/portraits/men/32.jpg'},
    imageStyle: {opacity: 0.6},
    backgroundColor: Colors.black,
    size: 60,
  },
  {
    title: 'Image Style: Opacity 1',
    source: {uri: 'https://randomuser.me/api/portraits/men/32.jpg'},
    imageStyle: {opacity: 1},
    backgroundColor: Colors.black,
    size: 60,
  },
];

// 4. 角标 (Badges)
const badgeExamples: Example[] = [
  {
    title: 'Badge: Top Right (Count)',
    label: 'TR',
    badgeProps: {label: '1', backgroundColor: Colors.red30},
    badgePosition: 'TOP_RIGHT',
    size: 50,
  },
  {
    title: 'Badge: Top Left (Icon)',
    source: {uri: 'https://randomuser.me/api/portraits/women/60.jpg'},
    badgeProps: {icon: star, backgroundColor: Colors.yellow30, size: 20},
    badgePosition: 'TOP_LEFT',
    size: 50,
  },
  {
    title: 'Badge: Bottom Right (Style)',
    label: 'BR',
    badgeProps: {
      size: 15,
      backgroundColor: Colors.green30,
      borderWidth: 2,
      borderColor: Colors.white,
    },
    badgePosition: 'BOTTOM_RIGHT',
    size: 50,
  },
  {
    title: 'Badge: Bottom Left',
    label: 'BL',
    badgeProps: {size: 15, backgroundColor: Colors.grey30},
    badgePosition: 'BOTTOM_LEFT',
    size: 50,
  },
];

// 5. 状态与在线 (Status & Online)
const statusExamples: Example[] = [
  {
    title: 'isOnline: True',
    source: {uri: 'https://randomuser.me/api/portraits/men/64.jpg'},
    isOnline: true,
    size: 60,
  },
  {
    title: 'isOnline: True',
    source: {uri: 'https://randomuser.me/api/portraits/men/64.jpg'},
    isOnline: false,
    size: 60,
  },
  {
    title: 'Status: Offline',
    label: 'Test',
    status: 'OFFLINE', // StatusModes
    size: 60,
  },
  {
    title: 'Status: Away',
    label: 'Test',
    status: 'AWAY', // StatusModes
    size: 60,
  },
];

// 6. 丝带 (Ribbon)
const ribbonExamples: Example[] = [
  {
    title: 'Ribbon: Label PRO',
    source: {uri: 'https://randomuser.me/api/portraits/women/20.jpg'},
    ribbonLabel: 'PRO',
    ribbonStyle: {backgroundColor: Colors.purple30},
    ribbonLabelStyle: {fontWeight: 'bold', color: Colors.white},
    size: 80,
  },
  {
    title: 'Ribbon: Label Online',
    source: {uri: 'https://randomuser.me/api/portraits/women/20.jpg'},
    ribbonLabel: 'Online',
    ribbonStyle: {backgroundColor: Colors.green30},
    ribbonLabelStyle: {fontWeight: 'normal', color: Colors.black},
    size: 80,
  },
  {
    title: 'Custom Ribbon: JSX Element VIP',
    label: 'CUST',
    size: 80,
    customRibbon: (
      <View
        style={{
          position: 'absolute',
          top: 0,
          right: 0,
          backgroundColor: Colors.blue30,
          padding: 2,
          borderRadius: 4,
        }}>
        <Text text100 white>
          VIP
        </Text>
      </View>
    ),
  },
  {
    title: 'Custom Ribbon: JSX Element SVIP',
    label: 'CUST',
    size: 80,
    customRibbon: (
      <View
        style={{
          position: 'absolute',
          top: 50,
          right: -30,
          backgroundColor: Colors.yellow30,
          padding: 2,
          borderRadius: 0,
        }}>
        <Text text100 white>
          SVIP
        </Text>
      </View>
    ),
  },
];

const advancedExamples: Example[] = [
  {
    title: 'Animate: Fade In (3s)\nimageProps: {animationDuration: 3000}',
    source: {
      uri: 'https://images.pexels.com/photos/19000252/pexels-photo-19000252.jpeg?auto=compress&cs=tinysrgb&w=600',
    },
    animate: true,
    imageProps: {animationDuration: 3000},
    size: 60,
  },
  {
    title: 'Animate: Fade In (1s)\nimageProps: {animationDuration: 1000}',
    source: {
      uri: 'https://images.pexels.com/photos/19000252/pexels-photo-19000252.jpeg?auto=compress&cs=tinysrgb&w=600',
    },
    animate: true,
    imageProps: {animationDuration: 1000},
    size: 60,
  },
  {
    title: 'Animate: Fade In False',
    source: {
      uri: 'https://images.pexels.com/photos/19000252/pexels-photo-19000252.jpeg?auto=compress&cs=tinysrgb&w=600',
    },
    animate: false,
    imageProps: {animationDuration: 1000},
    size: 60,
  },
  {
    title: 'Truncation: Clip',
    label: 'SuperLongLabelName',
    labelEllipsizeMode: 'clip',
    backgroundColor: Colors.cyan30,
    size: 60,
  },
  {
    title: 'Truncation: Head',
    label: 'SuperLongLabelName',
    labelEllipsizeMode: 'head',
    backgroundColor: Colors.cyan30,
    size: 60,
  },
  {
    title: 'Truncation: Head',
    label: 'SuperLongLabelName',
    labelEllipsizeMode: 'tail',
    backgroundColor: Colors.cyan30,
    size: 60,
  },
  {
    title: 'Event: onPress Alert',
    label: 'Tap',
    backgroundColor: Colors.orange30,
    size: 60,
    onPress: () => Alert.alert('OnPress Triggered', 'Avatar was pressed!'),
  },
];

export default class AvatarsScreen extends Component {
  state = {
    animationKey: 0,
    loadStartStatus: 'Wait for start...',
    loadEndStatus: 'Wait for end...',
    loadErrorStatus: 'Wait for error...',
    nativeImageErrorStatus: 'Wait for native error...', 
  };

  refreshAnimations = () => {
    this.setState({
        animationKey: this.state.animationKey + 1,
        loadStartStatus: 'Wait for start...',
        loadEndStatus: 'Wait for end...',
        loadErrorStatus: 'Wait for error...',
        nativeImageErrorStatus: 'Wait for native error...', 
    });
  };

  onAvatarPress = (item: any) => {
    if (item.onPress) {
      item.onPress();
      return;
    }

    const {title, source, label} = item;
    const uri = _.get(source, 'uri');
    const isGravatar = !!uri && AvatarHelper.isGravatarUrl(uri);
    const patchedGravatar = isGravatar
      ? AvatarHelper.patchGravatarUrl(uri)
      : undefined;
    const message = `Label: ${label}\n\nImage-source: ${uri}\n\nIs Gravatar: ${isGravatar}\n\n${
      patchedGravatar ? `Patched-uri: ${patchedGravatar}` : ''
    }`;
    Alert.alert(title, message);
  };

  renderSection = (title: string, data: Example[], extraContent?: React.ReactNode) => {
    return (
      <TestCase itShould={title}>
        <View style={styles.sectionContainer}>
          {extraContent && (
             <View style={{marginBottom: 10}}>
                {extraContent}
             </View>
          )}
          {_.map(data, (example, i) => (
            <View key={i} style={styles.itemContainer}>
              <Text $textDefault style={styles.itemTitle}>
                {example.title}
              </Text>
              <Avatar
                containerStyle={{marginVertical: 5}}
                {...example}
                onPress={() => this.onAvatarPress(example)}
              />
            </View>
          ))}
        </View>
      </TestCase>
    );
  };

  render() {
    const animatedAdvancedExamples = advancedExamples.map((item, index) => {
        if (index <= 2) { 
            return {
                ...item,
                key: `anim-${this.state.animationKey}-${index}`
            } as Example;
        }
        return item;
    });

    return (
      <TestSuite name="Avatar">
        <ScrollView contentContainerStyle={styles.container}>
          {this.renderSection(
            'Basic Content: Source, Label, Name, Colors',
            contentExamples,
          )}
          {this.renderSection(
            'Auto Colors: Hash generation & Config',
            autoColorExamples,
          )}
          {this.renderSection('Styling & Sizing', styleExamples)}
          {this.renderSection(
            'Badges: Positions & Types',
            badgeExamples,
          )}
          {this.renderSection('Status: Online, Offline, Away', statusExamples)}
          {this.renderSection('Ribbons: Standard & Custom', ribbonExamples)}
          
          {this.renderSection(
            'Advanced: Animation, Truncation, Events',
            animatedAdvancedExamples,
            <Button 
                label="Refresh Animations & Callbacks"
                size={Button.sizes.small}
                onPress={this.refreshAnimations}
                backgroundColor={Colors.blue30}
            />
          )}

          <TestCase itShould="Image Load Callbacks (Visual Feedback)">
            <View style={styles.sectionContainer}>
                
                <View style={styles.itemContainer}>
                    <View style={{flex: 1, paddingRight: 10}}>
                        <Text $textDefault style={styles.itemTitle}>Test: onImageLoadStart</Text>
                        <Text text90 color={Colors.grey40}>{this.state.loadStartStatus}</Text>
                    </View>
                    <Avatar 
                        key={`start-${this.state.animationKey}`}
                        size={50}
                        source={{uri: 'https://randomuser.me/api/portraits/women/44.jpg'}}
                        onImageLoadStart={() => this.setState({loadStartStatus: 'Callback Fired: START'})}
                    />
                </View>

                <View style={styles.itemContainer}>
                    <View style={{flex: 1, paddingRight: 10}}>
                        <Text $textDefault style={styles.itemTitle}>Test: onImageLoadEnd</Text>
                        <Text text90 color={Colors.green30}>{this.state.loadEndStatus}</Text>
                    </View>
                    <Avatar 
                        key={`end-${this.state.animationKey}`}
                        size={50}
                        source={{uri: 'https://randomuser.me/api/portraits/men/32.jpg'}}
                        onImageLoadEnd={() => this.setState({loadEndStatus: 'Callback Fired: END'})}
                    />
                </View>

                {/* 1. Avatar 组件测试组 */}
                <View style={styles.itemContainer}>
                    <View style={{flex: 1, paddingRight: 10}}>
                        <Text $textDefault style={styles.itemTitle}>Test: onImageLoadError</Text>
                        <Text text90 color={Colors.red30}>{this.state.loadErrorStatus}</Text>
                    </View>
                    <Avatar 
                        key={`error-${this.state.animationKey}`}
                        size={50}
                        backgroundColor={Colors.grey60}
                        source={{uri: 'http://127.0.0.1:65432/fail.jpg'}}
                        onImageLoadError={(e) => {
                            console.log('Avatar Error Event:', e.nativeEvent);
                            this.setState({loadErrorStatus: 'Callback Fired: ERROR'});
                        }}
                    />
                </View>

                {/* 2. 原生 Image 组件对照组 (Control Group) */}
                <View style={styles.itemContainer}>
                    <View style={{flex: 1, paddingRight: 10}}>
                        <Text $textDefault style={styles.itemTitle}>Control: Native Image onError</Text>
                        <Text text90 color={Colors.orange30}>{this.state.nativeImageErrorStatus}</Text>
                    </View>
                    <Image
                        key={`native-error-${this.state.animationKey}`}
                        source={{uri: 'http://127.0.0.1:65432/fail.jpg'}}
                        style={{width: 50, height: 50, backgroundColor: Colors.grey60, borderRadius: 25}}
                        onError={(e) => {
                            console.log('Native Image Error Event:', e.nativeEvent);
                            this.setState({nativeImageErrorStatus: 'Callback Fired: ERROR'});
                        }}
                    />
                </View>

            </View>
          </TestCase>
          <TestCase itShould="Support testID prop for Automation">
            <View style={styles.sectionContainer}>
                <View style={styles.itemContainer}>
                    <View style={{flex: 1, paddingRight: 10}}>
                        <Text $textDefault style={styles.itemTitle}>testID: 'avatar_test_uid'</Text>
                        <Text text90 color={Colors.grey40}>
                           Set testID='avatar_test_uid'. Use Layout Inspector to verify accessibility identifier.
                        </Text>
                    </View>
                    <Avatar 
                        size={50}
                        label="ID"
                        backgroundColor={Colors.violet30}
                        testID="avatar_test_uid"
                        onPress={() => Alert.alert('Info', 'This Avatar has a testID')}
                    />
                </View>
            </View>
          </TestCase>

        </ScrollView>
      </TestSuite>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    padding: 20,
    backgroundColor: Colors.black,
  },
  sectionContainer: {
    padding: 10,
    backgroundColor: Colors.$backgroundDefault,
  },
  itemContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginBottom: 15,
    borderBottomWidth: 1,
    borderBottomColor: Colors.$outlineDefault,
    paddingBottom: 10,
  },
  itemTitle: {
    ...Typography.text80,
    flex: 1,
    marginRight: 10,
  },
});